package so.raw.rsposter;

import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;

import java.util.*;
import java.util.concurrent.*;

/**
 * Created by zyw on 2015/9/17.
 * 为避免runOnChildThread执行过多次，采用线程池管理,这是子任务的现成管理类
 */
public class RSTaskManager {
    ThreadPoolExecutor mThreadPool;
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2 + 1;
    private static final int MAX_POOL_SIZE = (int) (CORE_POOL_SIZE * 1.5);
    private static final int KEEP_ALIVE_TIME = 1;
    private static final TimeUnit ALIVE_TIME_UNIT = TimeUnit.SECONDS;
    public static Map<RSMSGHandler, LinkedList<RSTask>> hMap; // 处理器 -> runnable 对象列表
    public static final int WAITING_QUEUE_LENGTH = 1000;
    private Handler mHandler; // 如果运行在主线程，需要此对象
    public boolean isBusy;

    private RSTaskManager(Handler handler) {
        //创建线程池
        this.mHandler = handler;
        mThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE, KEEP_ALIVE_TIME, ALIVE_TIME_UNIT,
                new LinkedBlockingQueue<>(WAITING_QUEUE_LENGTH), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            }
        });
        hMap = Collections.synchronizedMap(new LinkedHashMap<RSMSGHandler, LinkedList<RSTask>>()); // 处理器 -> runnable 对象列表
    }

    private static RSTaskManager mInstance;

    /**
     * 初始化任务管理对象
     * @param handler
     */
    public static void init(Handler handler) {
        mInstance = new RSTaskManager(handler);
    }
    public static RSTaskManager getInstance(){
        if(mInstance == null)
            throw  new IllegalStateException("线程管理对象还未初始化");
        return mInstance;
    }

    //增加任务
    public void runTask(RSTask task) {
        try {
            if (task.mChildRunner != null)
                mThreadPool.execute(task.mChildRunner);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (task.mMainThreadRunner != null) {
                   mHandler.post(task.mMainThreadRunner);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                putTaskInList(task);
            }
        }
    }

    //任务管理容器
    private void putTaskInList(RSTask task) {
        try {
            hMap.get(task.mTag).add(task);
        } catch (Exception e) {
            LinkedList<RSTask> tasks = new LinkedList<>();
            tasks.add(task);
            hMap.put(task.mTag, tasks);
        }
    }

    //从列表中移除消息
    public void removeTastskFromList(Object msgType, RSMSGHandler handler) {
        try {
            LinkedList<RSTask> tasks = hMap.get(handler);
            for (RSTask task : tasks) {
                if (task.msg.getType().equals(msgType)) {
                    hMap.get(handler).remove(task);
                }
            }
        } catch (Exception e) {

        }
    }

    public void clearTasks(){
        if(mThreadPool.getActiveCount() == 0){
            try{
                for(Map.Entry<RSMSGHandler,LinkedList<RSTask>> men : hMap.entrySet()){
                    men.getValue().clear();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //删除任务
    public void removeTask(Object msgType, RSMSGHandler handler) {
        try {
            LinkedList<RSTask> tasks = hMap.get(handler);
            if (tasks == null || tasks.size() < 0)
                return;
            for (int i = 0; i < tasks.size(); i++) {
                RSTask task = tasks.get(i);
                {
                    try {
                        if (task.msg.getType().equals(msgType)) {
                            mThreadPool.remove(task.mChildRunner);
                        }
                    } catch (Exception ex) {
                    } finally {
                        try {
                            if (task.msg.getType().equals(msgType)) {
                                mHandler.removeCallbacks(task.mMainThreadRunner);
                            }
                        } catch (Exception e1) {

                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            removeTastskFromList(msgType, handler);
        }
    }

    //拿到线程池对象
    public synchronized boolean isBusy(){
       return isBusy;
    }

    public void finishTask(Object type, RSMSGHandler mTag) {
        removeTastskFromList(type, mTag);
        RSPoster.condition.signalAll();
    }
}
